package com.example.blogdemo.controller;

import com.example.blogdemo.entity.Article;
import com.example.blogdemo.entity.ArticleTag;
import com.example.blogdemo.entity.HostHolder;
import com.example.blogdemo.entity.Tag;
import com.example.blogdemo.entity.User;
import com.example.blogdemo.entity.ViewObject;
import com.example.blogdemo.repository.ArticleRepository;
import com.example.blogdemo.service.ArticleService;
import com.example.blogdemo.service.JedisService;
import com.example.blogdemo.service.TagService;
import com.example.blogdemo.util.JblogUtil;
import com.example.blogdemo.util.RedisKeyUntil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author Anita
 * @Date 2017/12/28 17:27
 */
@Controller
@Slf4j
public class PersonController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private TagService tagService;
    @Autowired
    private JedisService jedisService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private ArticleRepository articleRepository;


    @RequestMapping("/person/article")
    public String personArticle(@RequestParam("userId")Integer userId, Model model){
        List<ViewObject> vos = new LinkedList<>();
        List<Article> articles = articleService.getArticlesByUserId(userId,0,4);
        for(Article article:articles){
            ViewObject vo = new ViewObject();
            List<Tag> tags = tagService.getTagByArticleId(article.getId());
            String clickCount = jedisService.get(RedisKeyUntil.getClickCountKey("/article/"+article.getId()));
            if(clickCount==null){
                clickCount = "0";
            }

            vo.set("clickCount",clickCount);
            vo.set("article",article);
            vo.set("tags",tags);
            vos.add(vo);
        }
        model.addAttribute("vos",vos);

        List<Tag> tags = tagService.getTagByUserId(userId);
        model.addAttribute("tags",tags);

        ViewObject pagination = new ViewObject();
        List<Article> articleTotal = articleService.getArticlesByUserId(userId);
        int count = articleTotal.size();
        pagination.set("current",1);
        pagination.set("nextPage",2);
        pagination.set("lastPage",count/4+1);
        model.addAttribute("pagination",pagination);

        User user = hostHolder.getUser();
        if(user==null||"admin".equals(user.getRole())){
            model.addAttribute("create",1);
        }else{
            model.addAttribute("create",0);
        }

        ViewObject categoryCount = new ViewObject();
        Map<String,Integer> maps = new HashMap<>();
        if(!articleTotal.isEmpty()) {
            for (Article article : articleTotal) {
                String categoryCh = article.getCategory();
                String category = JblogUtil.categoryMap.get(categoryCh);
                if (!maps.containsKey(category)) {
                    maps.put(category,1);
                } else {
                    maps.put(category, maps.get(category)+1);
                }
            }

            Set<String> keys = maps.keySet();
            for(String key:keys){
                categoryCount.set(key,maps.get(key));
            }
        }
        model.addAttribute("categoryCount",categoryCount);


        ViewObject clickCount =  new ViewObject();
        String currentPage = jedisService.get(RedisKeyUntil.getClickCountKey("/person/article"));
        String sumPage = jedisService.get(RedisKeyUntil.getClickCountKey("SUM"));
        clickCount.set("currentPage",currentPage);
        clickCount.set("sumPage",sumPage);
        model.addAttribute("clickCount",clickCount);


        List<Article> hotArticles = new ArrayList<>();
        Set<String> set = jedisService.zrevrange("hotArticles", 0, 6);
        for(String str:set){
            int articleId = Integer.parseInt((str.split(":"))[1]);
            Article article = articleService.getArticleById(articleId);
            hotArticles.add(article);
        }
        model.addAttribute("hotArticles", hotArticles);

        return "person";
    }

    @RequestMapping("/person/page/{pageId}")
    public String personarticlepage(Model model, @PathVariable("pageId")int pageId,@RequestParam("userId")int userId){
        List<ViewObject> vos = new LinkedList<>();
        List<Article> articles = articleService.getArticlesByUserId(userId,pageId-1,4);
        for(Article article:articles){
            ViewObject vo = new ViewObject();
            List<Tag> tags = tagService.getTagByArticleId(article.getId());
            String clickCount = jedisService.get(RedisKeyUntil.getClickCountKey("/article/"+article.getId()));
            if(clickCount==null){
                clickCount = "0";
            }

            vo.set("clickCount",clickCount);
            vo.set("article",article);
            vo.set("tags",tags);
            vos.add(vo);
        }
        model.addAttribute("vos",vos);

        List<Tag> tags = tagService.getTagByUserId(userId);
        model.addAttribute("tags",tags);

        ViewObject pagination = new ViewObject();
        List<Article> articleTotal = articleService.getArticlesByUserId(userId);
        int count = articleTotal.size();
        pagination.set("current",pageId);
        pagination.set("nextPage",pageId+1);
        pagination.set("prePage",pageId-1);
        pagination.set("lastPage",count/4+1);
        model.addAttribute("pagination",pagination);

        User user = hostHolder.getUser();
        if(user==null||"admin".equals(user.getRole())){
            model.addAttribute("create",1);
        }else{
            model.addAttribute("create",0);
        }


        ViewObject categoryCount = new ViewObject();
        Map<String,Integer> maps = new HashMap<>();
        if(!articleTotal.isEmpty()) {
            for (Article article : articleTotal) {
                String categoryCh = article.getCategory();
                String category = JblogUtil.categoryMap.get(categoryCh);
                if (!maps.containsKey(category)) {
                    maps.put(category,1);
                } else {
                    maps.put(category, maps.get(category)+1);
                }
            }

            Set<String> keys = maps.keySet();
            for(String key:keys){
                categoryCount.set(key,maps.get(key));
            }
        }
        model.addAttribute("categoryCount",categoryCount);

        ViewObject clickCount =  new ViewObject();
        String currentPage = jedisService.get(RedisKeyUntil.getClickCountKey("/person/page/"+pageId));
        String sumPage = jedisService.get(RedisKeyUntil.getClickCountKey("SUM"));
        clickCount.set("currentPage",currentPage);
        clickCount.set("sumPage",sumPage);
        model.addAttribute("clickCount",clickCount);


        List<Article> hotArticles = new ArrayList<>();
        Set<String> set = jedisService.zrevrange("hotArticles", 0, 6);
        for(String str:set){
            int articleId = Integer.parseInt((str.split(":"))[1]);
            Article article = articleService.getArticleById(articleId);
            hotArticles.add(article);
        }
        model.addAttribute("hotArticles", hotArticles);

        return "person";
    }


    @RequestMapping(value = "/person/category/{categoryName}",method = RequestMethod.GET)
    public String category(Model model,@PathVariable("categoryName")String categoryName,@RequestParam("pageId") int pageId,@RequestParam("userId")Integer userId){
        List<Article> articles= articleService.getArticlesByCategoryAndUserId(categoryName,userId,(pageId-1)*4,4);
        List<ViewObject> vos = new ArrayList<>();
        for(Article article:articles){
            ViewObject vo = new ViewObject();
            List<Tag> tags = tagService.getTagByArticleId(article.getId());
            String clickCount = jedisService.get(RedisKeyUntil.getClickCountKey("/article/"+article.getId()));
            if(clickCount==null){
                clickCount="0";
            }
            vo.set("clickCount",clickCount);
            vo.set("tags",tags);
            vo.set("article",article);
            vos.add(vo);
        }
        model.addAttribute("vos",vos);

        ViewObject pagination = new ViewObject();
        int count = articleService.getArticlesByCategoryAndUserId(categoryName,userId).size();
        pagination.set("current",pageId);
        pagination.set("nextPage",pageId+1);
        pagination.set("prePage",pageId-1);
        pagination.set("lastPage",count/4+1);
        model.addAttribute("pagination",pagination);

        User user = hostHolder.getUser();
        if(user==null||"admin".equals(user.getRole())){
            model.addAttribute("create",1);
        }else{
            model.addAttribute("create",0);
        }

        List<Tag> tags = tagService.getTagByUserId(userId);
        model.addAttribute("tags",tags);

        model.addAttribute("category",categoryName);


        ViewObject categoryCount = new ViewObject();
        Map<String,Integer> maps = new HashMap<>();
        List<Article> articleTotal = articleService.getArticlesByUserId(userId);
        if(!articleTotal.isEmpty()) {
            for (Article article : articleTotal) {
                String categoryCh = article.getCategory();
                String category = JblogUtil.categoryMap.get(categoryCh);
                if (!maps.containsKey(category)) {
                    maps.put(category,1);
                } else {
                    maps.put(category, maps.get(category)+1);
                }
            }

            Set<String> keys = maps.keySet();
            for(String key:keys){
                categoryCount.set(key,maps.get(key));
            }
        }
        model.addAttribute("categoryCount",categoryCount);



        ViewObject clickCount = new ViewObject();
        String currentPage = jedisService.get(RedisKeyUntil.getClickCountKey("/person/category/"+categoryName));
        String sumPage = jedisService.get(RedisKeyUntil.getClickCountKey("SUM"));
        clickCount.set("currentPage",currentPage);
        clickCount.set("sumPage",sumPage);
        model.addAttribute("clickCount",clickCount);

        List<Article> hotArticles = new ArrayList<>();
        Set<String> set = jedisService.zrevrange("hotArticles",0,6);
        for(String str:set){
            int articleId = Integer.parseInt(str.split(":")[1]);
            Article article = articleService.getArticleById(articleId);
            hotArticles.add(article);
        }
        model.addAttribute("hotArticles",hotArticles);

        return "categoryperson";
    }

    @RequestMapping(value = "/person/tag/{tagId}",method = RequestMethod.GET)
    public String tag(Model model, @PathVariable("tagId")int tagId, @RequestParam("pageId")int pageId,@RequestParam("userId")Integer userId){
        List<Article> articles = articleService.getArticleByTagAndUserId(tagId,userId,(pageId-1)*4,4);
        List<ViewObject> vos = new ArrayList<>();
        for (Article article:articles){
            ViewObject vo = new ViewObject();
            List<Tag> tags = tagService.getTagByArticleId(article.getId());
            String clickCount = jedisService.get(RedisKeyUntil.getClickCountKey("/article/"+article.getId()));
            if (clickCount==null)
                clickCount = "0";
            vo.set("clickCount",clickCount);
            vo.set("article",article);
            vo.set("tags",tags);
            vos.add(vo);
        }
        model.addAttribute("vos",vos);

        ViewObject pagination = new ViewObject();
        int count = articles.size();

        pagination.set("current",pageId);
        pagination.set("nextPage",pageId+1);
        pagination.set("prePage",pageId-1);
        pagination.set("lastPage",count/4+1);

        User user = hostHolder.getUser();
        if (user==null||"admin".equals(user.getRole())){
            model.addAttribute("create",1);
        }else {
            model.addAttribute("create",0);
        }

        List<Tag> tags = tagService.getTagByUserId(userId);
        model.addAttribute("tags",tags);
        model.addAttribute("pagination",pagination);
        model.addAttribute("tagId",tagId);

        ViewObject categoryCount = new ViewObject();
        Map<String,Integer> maps = new HashMap<>();
        List<Article> articleTotal = articleService.getArticlesByUserId(userId);
        if(!articleTotal.isEmpty()) {
            for (Article article : articleTotal) {
                String categoryCh = article.getCategory();
                String category = JblogUtil.categoryMap.get(categoryCh);
                if (!maps.containsKey(category)) {
                    maps.put(category,1);
                } else {
                    maps.put(category, maps.get(category)+1);
                }
            }

            Set<String> keys = maps.keySet();
            for(String key:keys){
                categoryCount.set(key,maps.get(key));
            }
        }
        model.addAttribute("categoryCount",categoryCount);

        ViewObject clickCount = new ViewObject();
        String currentPage = jedisService.get(RedisKeyUntil.getClickCountKey("/person/tag/"+tagId));
        String sumPage = jedisService.get(RedisKeyUntil.getClickCountKey("SUM"));
        clickCount.set("currentPage",currentPage);
        clickCount.set("sumPage",sumPage);
        model.addAttribute("clickCount",clickCount);

        List<Article> hotArticles = new ArrayList<>();
        Set<String> set = jedisService.zrevrange("hotArticles",0,6);
        for (String str : set){
            int articleId = Integer.parseInt(str.split(":")[1]);
            Article article = articleService.getArticleById(articleId);
            hotArticles.add(article);
        }
        model.addAttribute("hotArticles",hotArticles);
        log.info("hotArticles:{}",hotArticles.toString());

        return "tagperson";
    }

    @RequestMapping("/update/{articleId}")
    public String updateSingleArticle(Model model, @PathVariable("articleId")int articleId){
        Article article = articleService.getArticleById(articleId);
        model.addAttribute("article",article);
        User user = hostHolder.getUser();
        if(user==null||"admin".equals(user.getRole())){
            model.addAttribute("create",1);
        }else{
            model.addAttribute("create",0);
        }
        return "update";
    }

    @RequestMapping("/person/articleAdd/{articleId}")
    public String addArticle(@RequestParam("title")String title, @RequestParam("describe")String describe,
                             @RequestParam("content")String content,@PathVariable("articleId")Integer articleId){
        Article article = articleRepository.findById(articleId);
        article.setTitle(title);
        article.setDescribes(describe);
        article.setCreatedDate(new Date());
        article.setContent(JblogUtil.transfer(content));
        article.setContentRaw(content); //存rawcontent
        articleRepository.save(article);

        return "redirect:/";
    }


}
